package com.andy.process.interfaces.impl;

import com.andy.common.entity.Configuration;
import com.andy.common.entity.Bean;
import com.andy.common.entity.Schema;
import com.andy.common.util.ExcelUtil;
import com.andy.process.fork.ParserTask;
import com.andy.process.interfaces.IDataParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;

/**
 * Created by Yuli_Yan on 2017/9/5.
 */
public class ExcelDataParser implements IDataParser<List<Bean>, List<String>> {
    private static final Logger LOG = LoggerFactory.getLogger(ExcelDataParser.class);
    private List<String> lines;
    private ForkJoinPool pool;
    private Schema schema;

    public ExcelDataParser(String path,Schema configuration) {
        lines = load(path);
        this.schema = configuration;
    }

    /**
     * use spark to map data
     *
     * @param source
     */
    public List<Bean> parser(Configuration source) {
        int size = lines.size();
        pool = new ForkJoinPool(size);
        ParserTask task = new ParserTask(lines,schema);
        Future<List<Bean>> result = pool.submit(task);
        try {
            List<Bean> Beans = result.get();
            return Beans;
        } catch (Exception e) {
            LOG.error("forkJoin parser data error,{}", e);
        }
        return null;
    }

    /**
     * load file from excel but speed is slow
     * nio cloud try
     *
     * @param path
     * @return
     */
    public List<String> load(String path) {
        lines = ExcelUtil.NioLoadFile(path);
        return lines;
    }
}
